package com.dbappsecurity.network.client.interceptor;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Arirus on 2017/8/18.
 */

public final class CommonParameterInterceptor implements Interceptor {
    private static String TAG = "CommonParameter";

    private Map<String, String> mParmsMap;

    private InterceptorHelper.ModifyParms modifyParms = null;

    @Deprecated
    /**
     * 统一使用接口来进行插入
     */
    public CommonParameterInterceptor(Map<String, String> parmsMap) {
        mParmsMap = parmsMap;
    }

    public CommonParameterInterceptor() {
        mParmsMap = new HashMap<>();
    }

    @Deprecated
    /**
     * 统一使用接口来进行插入
     */
    public CommonParameterInterceptor add(String Key, String Value) {
        mParmsMap.put(Key, Value);
        return this;
    }

    public void setModifyParms(InterceptorHelper.ModifyParms modifyParms) {
        this.modifyParms = modifyParms;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request orginalRequest = chain.request();
        Request modifyRequest;
        HttpUrl.Builder modifyUrlBuilder = orginalRequest.url().newBuilder();

        if (modifyParms != null) mParmsMap = modifyParms.modify(mParmsMap);

        for (String name : mParmsMap.keySet()) {
            modifyUrlBuilder.addQueryParameter(name, mParmsMap.get(name));
        }
        modifyRequest = orginalRequest.newBuilder().url(modifyUrlBuilder.build()).build();

        return chain.proceed(modifyRequest);
    }
}
